using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Configuration;

/// <summary>
/// 应用启动阶段的专用日志服务
/// 用于在依赖注入容器完全初始化之前提供日志支持
/// </summary>
public static class StartupLogger
{
    private static Microsoft.Extensions.Logging.ILogger? _logger;
    private static readonly List<(LogLevel Level, string Message, Exception? Exception)> _bufferedLogs = new();
    private static bool _isInitialized = false;

    /// <summary>
    /// 初始化启动日志器
    /// </summary>
    /// <param name="serviceProvider">服务提供者</param>
    public static void Initialize(IServiceProvider serviceProvider)
    {
        try
        {
            _logger = serviceProvider.GetService<ILogger<Program>>();
            _isInitialized = true;
            
            // 输出缓冲的日志
            FlushBufferedLogs();
        }
        catch (Exception ex)
        {
            // 如果获取日志器失败，仍然缓存日志
            BufferLog(LogLevel.Error, $"启动日志器初始化失败: {ex.Message}", ex);
        }
    }

    /// <summary>
    /// 记录配置信息
    /// </summary>
    public static void LogConfigurationInfo(string component, string message, object? details = null)
    {
        var formattedMessage = details != null 
            ? $"🔧 配置 {component}: {message}, 详情: {@details}"
            : $"🔧 配置 {component}: {message}";
            
        LogOrBuffer(LogLevel.Information, formattedMessage);
    }

    /// <summary>
    /// 记录配置警告
    /// </summary>
    public static void LogConfigurationWarning(string component, string message, object? details = null)
    {
        var formattedMessage = details != null
            ? $"⚠️ 配置警告 {component}: {message}, 详情: {@details}"
            : $"⚠️ 配置警告 {component}: {message}";
            
        LogOrBuffer(LogLevel.Warning, formattedMessage);
    }

    /// <summary>
    /// 记录配置错误
    /// </summary>
    public static void LogConfigurationError(string component, string message, Exception? ex = null, object? details = null)
    {
        var formattedMessage = details != null
            ? $"❌ 配置错误 {component}: {message}, 详情: {@details}"
            : $"❌ 配置错误 {component}: {message}";
            
        LogOrBuffer(LogLevel.Error, formattedMessage, ex);
    }

    /// <summary>
    /// 记录应用启动里程碑
    /// </summary>
    public static void LogStartupMilestone(string milestone, TimeSpan? elapsed = null)
    {
        var message = elapsed.HasValue 
            ? $"🚀 启动里程碑: {milestone} (耗时: {elapsed.Value.TotalMilliseconds:F2}ms)"
            : $"🚀 启动里程碑: {milestone}";
            
        LogOrBuffer(LogLevel.Information, message);
    }

    /// <summary>
    /// 记录性能指标
    /// </summary>
    public static void LogPerformanceMetric(string operation, TimeSpan elapsed, object? metadata = null)
    {
        var message = metadata != null
            ? $"⚡ 性能指标: {operation} 耗时 {elapsed.TotalMilliseconds:F2}ms, 元数据: {@metadata}"
            : $"⚡ 性能指标: {operation} 耗时 {elapsed.TotalMilliseconds:F2}ms";
            
        LogOrBuffer(LogLevel.Information, message);
    }

    /// <summary>
    /// 记录启动成功
    /// </summary>
    public static void LogStartupSuccess(TimeSpan totalStartupTime)
    {
        LogOrBuffer(LogLevel.Information, 
            $"🎉 应用启动成功! 总耗时: {totalStartupTime.TotalMilliseconds:F2}ms");
    }

    /// <summary>
    /// 记录启动失败
    /// </summary>
    public static void LogStartupFailure(Exception ex)
    {
        LogOrBuffer(LogLevel.Critical, 
            $"💥 应用启动失败: {ex.Message}", ex);
    }

    /// <summary>
    /// 记录启动错误
    /// </summary>
    public static void LogStartupError(string message, Exception? exception = null)
    {
        LogOrBuffer(LogLevel.Error, 
            $"❌ 启动错误: {message}", exception);
    }

    /// <summary>
    /// 记录权限配置
    /// </summary>
    public static void LogPermissionConfiguration(bool enabled, object? details = null)
    {
        var message = details != null
            ? $"🔐 权限配置: {(enabled ? "已启用" : "已禁用")}, 详情: {@details}"
            : $"🔐 权限配置: {(enabled ? "已启用" : "已禁用")}";
            
        LogOrBuffer(LogLevel.Information, message);
    }

    /// <summary>
    /// 内部方法：记录日志或缓存到缓冲区
    /// </summary>
    private static void LogOrBuffer(LogLevel level, string message, Exception? exception = null)
    {
        if (_isInitialized && _logger != null)
        {
            _logger.Log(level, exception, message);
        }
        else
        {
            BufferLog(level, message, exception);
        }
    }

    /// <summary>
    /// 缓存日志到内存缓冲区
    /// </summary>
    private static void BufferLog(LogLevel level, string message, Exception? exception = null)
    {
        lock (_bufferedLogs)
        {
            _bufferedLogs.Add((level, message, exception));
            
            // 限制缓冲区大小，避免内存泄漏
            if (_bufferedLogs.Count > 100)
            {
                _bufferedLogs.RemoveAt(0);
            }
        }
    }

    /// <summary>
    /// 输出所有缓冲的日志
    /// </summary>
    private static void FlushBufferedLogs()
    {
        if (_logger == null) return;

        lock (_bufferedLogs)
        {
            foreach (var (level, message, exception) in _bufferedLogs)
            {
                _logger.Log(level, exception, message);
            }
            _bufferedLogs.Clear();
        }
    }

    /// <summary>
    /// 获取缓冲的日志数量（用于监控）
    /// </summary>
    public static int GetBufferedLogCount()
    {
        lock (_bufferedLogs)
        {
            return _bufferedLogs.Count;
        }
    }
}

/// <summary>
/// 基础设施层专用日志扩展
/// 提供统一的基础设施组件日志记录方法
/// </summary>
public static class InfrastructureLoggingExtensions
{
    /// <summary>
    /// 记录缓存配置
    /// </summary>
    public static void LogCacheConfiguration(this Microsoft.Extensions.Logging.ILogger logger, 
        string cacheType, string status, object? configuration = null)
    {
        if (configuration != null)
        {
            logger.LogInformation("💾 缓存配置: {CacheType} - {Status}, 配置: {@Configuration}", 
                cacheType, status, configuration);
        }
        else
        {
            logger.LogInformation("💾 缓存配置: {CacheType} - {Status}", cacheType, status);
        }
    }

    /// <summary>
    /// 记录缓存操作性能
    /// </summary>
    public static void LogCachePerformance(this Microsoft.Extensions.Logging.ILogger logger,
        string operation, string key, TimeSpan elapsed, bool hit = false)
    {
        var hitStatus = hit ? "命中" : "未命中";
        logger.LogInformation("💾 缓存性能: {Operation} {Key} - {HitStatus}, 耗时: {ElapsedMs:F2}ms",
            operation, key, hitStatus, elapsed.TotalMilliseconds);
    }

    /// <summary>
    /// 记录数据库配置
    /// </summary>
    public static void LogDatabaseConfiguration(this Microsoft.Extensions.Logging.ILogger logger, 
        string dbType, string maskedConnection, object? settings = null)
    {
        if (settings != null)
        {
            logger.LogInformation("🗄️ 数据库配置: {DatabaseType} - {Connection}, 设置: {@Settings}", 
                dbType, maskedConnection, settings);
        }
        else
        {
            logger.LogInformation("🗄️ 数据库配置: {DatabaseType} - {Connection}", dbType, maskedConnection);
        }
    }

    /// <summary>
    /// 记录数据库操作性能
    /// </summary>
    public static void LogDatabasePerformance(this Microsoft.Extensions.Logging.ILogger logger,
        string operation, string entity, TimeSpan elapsed, int? recordCount = null)
    {
        if (recordCount.HasValue)
        {
            logger.LogInformation("🗄️ 数据库性能: {Operation} {Entity} - {RecordCount} 记录, 耗时: {ElapsedMs:F2}ms",
                operation, entity, recordCount.Value, elapsed.TotalMilliseconds);
        }
        else
        {
            logger.LogInformation("🗄️ 数据库性能: {Operation} {Entity} - 耗时: {ElapsedMs:F2}ms",
                operation, entity, elapsed.TotalMilliseconds);
        }
    }

    /// <summary>
    /// 记录健康检查配置
    /// </summary>
    public static void LogHealthCheckConfiguration(this Microsoft.Extensions.Logging.ILogger logger, 
        string service, string status, object? details = null)
    {
        if (details != null)
        {
            logger.LogInformation("❤️ 健康检查: {Service} - {Status}, 详情: {@Details}", 
                service, status, details);
        }
        else
        {
            logger.LogInformation("❤️ 健康检查: {Service} - {Status}", service, status);
        }
    }

    /// <summary>
    /// 记录权限配置
    /// </summary>
    public static void LogPermissionConfiguration(this Microsoft.Extensions.Logging.ILogger logger, 
        bool enabled, object? policies = null)
    {
        var status = enabled ? "已启用" : "未启用";
        var emoji = enabled ? "🔒" : "🔓";
        
        if (policies != null)
        {
            logger.LogInformation("{Emoji} 权限系统: {Status}, 策略: {@Policies}", 
                emoji, status, policies);
        }
        else
        {
            logger.LogInformation("{Emoji} 权限系统: {Status}", emoji, status);
        }
    }

    /// <summary>
    /// 记录中间件配置
    /// </summary>
    public static void LogMiddlewareConfiguration(this Microsoft.Extensions.Logging.ILogger logger,
        string middlewareName, string status, object? configuration = null)
    {
        if (configuration != null)
        {
            logger.LogInformation("🔧 中间件: {MiddlewareName} - {Status}, 配置: {@Configuration}",
                middlewareName, status, configuration);
        }
        else
        {
            logger.LogInformation("🔧 中间件: {MiddlewareName} - {Status}", middlewareName, status);
        }
    }

    /// <summary>
    /// 记录服务注册
    /// </summary>
    public static void LogServiceRegistration(this Microsoft.Extensions.Logging.ILogger logger,
        string serviceName, string serviceType, string lifetime)
    {
        logger.LogInformation("🔗 服务注册: {ServiceName} ({ServiceType}) - {Lifetime}",
            serviceName, serviceType, lifetime);
    }

    /// <summary>
    /// 记录配置加载
    /// </summary>
    public static void LogConfigurationLoad(this Microsoft.Extensions.Logging.ILogger logger,
        string configurationSource, string status, int settingsCount = 0)
    {
        logger.LogInformation("📋 配置加载: {ConfigurationSource} - {Status}, 配置项: {SettingsCount}",
            configurationSource, status, settingsCount);
    }

    /// <summary>
    /// 记录配置验证结果
    /// </summary>
    public static void LogConfigurationValidation(this Microsoft.Extensions.Logging.ILogger logger,
        string section, bool isValid, string[]? errors = null, string[]? warnings = null)
    {
        if (isValid)
        {
            logger.LogInformation("✅ 配置验证: {Section} - 通过", section);
        }
        else
        {
            logger.LogError("❌ 配置验证: {Section} - 失败, 错误: {@Errors}", section, errors ?? Array.Empty<string>());
        }

        if (warnings != null && warnings.Length > 0)
        {
            logger.LogWarning("⚠️ 配置警告: {Section} - 警告: {@Warnings}", section, warnings);
        }
    }

    /// <summary>
    /// 记录回退操作
    /// </summary>
    public static void LogFallback(this Microsoft.Extensions.Logging.ILogger logger,
        string component, string reason, string fallbackAction)
    {
        logger.LogWarning("🔄 回退操作: {Component} - {Reason}, 回退到: {FallbackAction}",
            component, reason, fallbackAction);
    }
}
